package com.example.xmlparsedemo

import android.content.Context
import android.content.Intent
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.DividerItemDecoration
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import kotlinx.android.synthetic.main.activity_list.*
import javax.xml.parsers.SAXParserFactory

class ListActivity : AppCompatActivity() {
    private var mType: Int? = 0

    companion object {
        const val EXTRA_TYPE = "EXTRA_TYPE";
        fun startThisActivity(context: Context, type: Int) {
            var intent = Intent(context, ListActivity::class.java)
            intent.putExtra(EXTRA_TYPE, type)
            context.startActivity(intent)
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_list)
        mType = intent.getIntExtra(EXTRA_TYPE, 0)
        rv_list.layoutManager = LinearLayoutManager(this)
        rv_list.addItemDecoration(DividerItemDecoration(this, DividerItemDecoration.VERTICAL))
        when (mType) {
            //sax解析
            1 -> {
                var list = saxParse()
                if (list != null) {
                    var listAdapter = ListAdapter(list)
                    rv_list.adapter = listAdapter
                    listAdapter.notifyDataSetChanged()
                }
            }
            //dom解析
            2 -> {
                var list = DomHelper.getList(this)
                if (list != null) {
                    var listAdapter = ListAdapter(list)
                    rv_list.adapter = listAdapter
                    listAdapter.notifyDataSetChanged()
                }
            }
            //pull解析
            3 -> {
                var list = PullHelper.getList(this)
                if (list != null) {
                    var listAdapter = ListAdapter(list)
                    rv_list.adapter = listAdapter
                    listAdapter.notifyDataSetChanged()
                }
            }
        }
    }

    fun saxParse(): MutableList<WxAccountBean>? {
        try {
            //获取输入流
            var inputStream = assets.open("demo.xml")
            //创建解析工具类
            var saxHelper = SAXHelper()
            //创建解析工厂类
            var saxParserFactory = SAXParserFactory.newInstance()
            //创建解析器
            var saxParser = saxParserFactory.newSAXParser()
            //将输入流与解析类传入并解析
            saxParser.parse(inputStream, saxHelper)
            inputStream.close()
            return saxHelper.getList()
        } catch (e: Exception) {
            e.printStackTrace()
            return null
        }

    }
}